import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/widgets.dart'; // 添加必要的导入以支持 ScrollDirection

import '../models/learning_item.dart';
import 'bottom_action_bar.dart';

class LearningCard extends StatefulWidget {
  final LearningItem item;
  final VoidCallback onLike;
  final VoidCallback onDislike;
  final VoidCallback onCategory;
  // 添加一个回调函数，用于通知父组件切换页面
  final VoidCallback? onPageSwitch;

  const LearningCard({
    super.key,
    required this.item,
    required this.onLike,
    required this.onDislike,
    required this.onCategory,
    this.onPageSwitch,
  });

  @override
  State<LearningCard> createState() => _LearningCardState();
}

class _LearningCardState extends State<LearningCard> {
  bool _isLiked = false;
  bool _isCollected = false;
  late FlutterTts flutterTts;
  bool _ttsSupported = true;

  @override
  void initState() {
    super.initState();
    _initTts();
  }

  void _initTts() async {
    // Web平台特殊处理
    if (kIsWeb) {
      try {
        flutterTts = FlutterTts();
        
        // 设置TTS参数
        await flutterTts.setLanguage("en-US");
        await flutterTts.setSpeechRate(0.5);
        await flutterTts.setVolume(1.0);
        await flutterTts.setPitch(1.0);
      } catch (e) {
        // Web平台可能不支持TTS
        print("TTS initialization failed on web: $e");
        setState(() {
          _ttsSupported = false;
        });
      }
    } else {
      flutterTts = FlutterTts();
      
      // 设置TTS参数
      await flutterTts.setLanguage("en-US");
      await flutterTts.setSpeechRate(0.5);
      await flutterTts.setVolume(1.0);
      await flutterTts.setPitch(1.0);
    }
  }

  void _onLikePressed() {
    setState(() => _isLiked = !_isLiked);
  }

  void _onCollectPressed() {
    setState(() => _isCollected = !_isCollected);
  }

  Future<void> _speakWord(String word) async {
    if (!_ttsSupported) return;
    
    try {
      await flutterTts.speak(word);
    } catch (e) {
      print("Error speaking word: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 内容区域
            Expanded(
              child: Center(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: _buildContent(),
                ),
              ),
            ),
            
            // 底部交互区域
            _buildBottomBar(),
          ],
        ),
      ),
    );
  }

  /// 处理内容点击事件
  void _handleContentTap(BuildContext context) {
    // 不再需要跳转到详情页，所有内容直接在卡片中展示
  }

  Widget _buildContent() {
    // 检查是否是电影类型的数据
    if (widget.item.contentRef != null && 
        widget.item.contentRef!.contains('films.json')) {
      // 这是一个电影条目，显示电影信息
      return _buildFilmContent();
    }
    // 检查是否是英文卡通类型的数据
    else if (widget.item.contentRef != null && 
        widget.item.contentRef!.contains('english_katong.json')) {
      // 这是一个英文卡通条目，显示英文卡通信息
      return _buildEnglishKatongContent();
    }
    // 检查是否是词汇单元类型的数据
    else if (widget.item.contentRef != null && 
        widget.item.contentRef!.contains('vocabulary_data')) {
      // 这是一个词汇单元，直接显示词汇列表
      return _buildVocabularyUnitContent();
    }
    // 检查是否是拼音类型的数据
    else if (widget.item.tags.contains('pinyin')) {
      // 这是一个拼音学习项，直接显示拼音详细内容
      return _buildPinyinContent();
    } else if (widget.item.type == ContentType.poem) {
      // 这是一个古诗类型，显示古诗信息
      return _buildPoemContent();
    } else if (widget.item.subject == 'English' && widget.item.module == 'Stories'){
      return _buildEnglishStoryContent();
    } else {
      // 默认内容展示
      return _buildNormalContent();
    }
  }

  Widget _buildNormalContent() {
    print("构建普通内容");
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题
          Text(
            widget.item.title,
            style: const TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.bold,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 10),
          
          // 信息
          if (widget.item.description != null && widget.item.description!.isNotEmpty)
            Text(
              widget.item.description!,
              style: const TextStyle(
                fontSize: 18,
                color: Colors.grey,
              ),
              textAlign: TextAlign.left,
            ),
          
          const SizedBox(height: 20),
          
          // 内容
          Text(
            widget.item.content,
            style: const TextStyle(
              fontSize: 20,
            ),
            textAlign: TextAlign.left,
          ),
        ],
      ),
    );
  }


  /// 构建英文故事内容显示
  Widget _buildEnglishStoryContent() {
    // 对于英文故事，内容包含英文和中文，用空行分隔
    final parts = widget.item.content.split('\ne-c-content\n');
    final englishContent = parts.isNotEmpty ? parts[0] : '';
    final chineseContent = parts.length > 1 ? parts.sublist(1).join('\n\n') : '';
    return SingleChildScrollView(
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标题
        Text(
          widget.item.title,
          style: const TextStyle(
            fontSize: 28,
            fontWeight: FontWeight.bold,
          ),
          textAlign: TextAlign.center,
        ),
        const SizedBox(height: 10),

        // 英文内容
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey.withOpacity(0.3)),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            englishContent,
            style: const TextStyle(
              fontSize: 16,
              height: 1.6,
              color: Colors.black87,
            ),
          ),
        ),
        const SizedBox(height: 20),
        // 中文题目
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.blue[50],
            border: Border.all(color: Colors.blue.withOpacity(0.3)),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            widget.item.description?? '英文故事',
            style: const TextStyle(
              fontSize: 16,
              height: 1.6,
              color: Colors.black87,
            ),
          ),
        ),
        const SizedBox(height: 20),
        // 中文翻译
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.blue[50],
            border: Border.all(color: Colors.blue.withOpacity(0.3)),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            chineseContent,
            style: const TextStyle(
              fontSize: 16,
              height: 1.6,
              color: Colors.black87,
            ),
          ),
        ),
      ],
    ),
    );
  }

  Widget _buildPoemContent() {
      // 为古诗类型构建专门的展示界面
      return SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 标题
            Text(
              widget.item.title,
              style: const TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 8),
            
            // 作者和朝代
            Text(
              '${widget.item.dynasty} · ${widget.item.author}',
              style: const TextStyle(
                fontSize: 18,
                color: Colors.grey,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            
            // 古诗内容
            Text(
              widget.item.content,
              style: const TextStyle(
                fontSize: 20,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            
            // 译文
            if (widget.item.translation != null && widget.item.translation!.isNotEmpty)
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey.shade300),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '译文',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      widget.item.translation!,
                      style: const TextStyle(
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
              ),
          ],
        ),
      );
  }

  Widget _buildFilmContent() {
    // 显示电影信息
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 电影标题
          Text(
            widget.item.title,
            style: const TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.bold,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 10),
          
          // 年级信息
          Text(
            '${widget.item.grade}年级',
            style: const TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 10),
          
          // 电影信息
          if (widget.item.description != null && widget.item.description!.isNotEmpty)
            Text(
              widget.item.description!,
              style: const TextStyle(
                fontSize: 18,
                color: Colors.grey,
              ),
              textAlign: TextAlign.center,
            ),
          
          const SizedBox(height: 20),
          
          // 剧情简介标题
          const Text(
            '剧情简介',
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
            ),
          ),
          
          const SizedBox(height: 10),
          
          // 剧情简介内容
          Text(
            widget.item.content,
            style: const TextStyle(
              fontSize: 20,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildEnglishKatongContent() {
    // 显示英文卡通信息
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 英文卡通标题
          Text(
            widget.item.title,
            style: const TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.bold,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 10),
          
          // 年级信息
          Text(
            '${widget.item.grade}年级',
            style: const TextStyle(
              fontSize: 16,
              color: Colors.grey,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 10),
          
          // 英文卡通信息
          if (widget.item.description != null && widget.item.description!.isNotEmpty)
            Text(
              widget.item.description!,
              style: const TextStyle(
                fontSize: 18,
                color: Colors.grey,
              ),
              textAlign: TextAlign.center,
            ),
          
          const SizedBox(height: 20),
          
          // 剧情简介标题
          const Text(
            '剧情简介',
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
            ),
          ),
          
          const SizedBox(height: 10),
          
          // 剧情简介内容
          Text(
            widget.item.content,
            style: const TextStyle(
              fontSize: 20,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildVocabularyUnitContent() {
    // 直接显示词汇列表
    return FutureBuilder<List<dynamic>>(
      future: _loadVocabularyData(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('加载失败: ${snapshot.error}'));
        } else if (snapshot.hasData) {
          final data = snapshot.data!;
          
          // 从item的ID中提取单元索引
          // ID格式为 "vocabulary_unit_X"，其中X是单元ID
          final idParts = widget.item.id.split('_');
          if (idParts.length < 3) {
            return const Center(child: Text('数据格式错误'));
          }
          
          final unitIdStr = idParts.last;
          final unitId = int.tryParse(unitIdStr);
          
          if (unitId == null) {
            return const Center(child: Text('无法解析单元ID'));
          }
          
          // 在JSON数据中查找匹配的单元
          Map<String, dynamic>? targetUnit;
          // 遍历所有vid组
          for (var vidGroup in data) {
            if (vidGroup is Map<String, dynamic>) {
              final List<dynamic> vocabulary = vidGroup['vocabulary'] ?? [];
              // 在每个vid组的vocabulary中查找目标单元
              for (var unit in vocabulary) {
                if (unit is Map<String, dynamic> && unit['id'] == unitId) {
                  targetUnit = unit;
                  break;
                }
              }
              if (targetUnit != null) break;
            }
          }
          
          if (targetUnit != null) {
            final words = List<Map<String, dynamic>>.from(targetUnit['words'] ?? []);
            
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 单元标题
                Text(
                  targetUnit['title'] ?? 'Unit ${unitId}',
                  style: const TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                ),
                
                const SizedBox(height: 8),
                
                // 单元描述
                if (targetUnit['description'] != null)
                  Text(
                    targetUnit['description'],
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.grey,
                    ),
                    textAlign: TextAlign.center,
                  ),
                
                const SizedBox(height: 16),
                
                // 词汇列表
                Expanded(
                  child: ListView.builder(
                    itemCount: words.length,
                    itemBuilder: (context, index) {
                      final word = words[index];
                      final englishWord = word['english'] ?? '';
                      return Card(
                        margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        child: ListTile(
                          title: Text(
                            englishWord,
                            style: const TextStyle(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          subtitle: Text(word['chinese'] ?? ''),
                          trailing: _ttsSupported 
                            ? IconButton(
                                icon: const Icon(Icons.volume_up),
                                onPressed: () => _speakWord(englishWord),
                              )
                            : null,
                        ),
                      );
                    },
                  ),
                ),
              ],
            );
          } else {
            return const Center(child: Text('未找到指定单元'));
          }
        } else {
          return const Center(child: Text('暂无数据'));
        }
      },
    );
  }

  Future<List<dynamic>> _loadVocabularyData() async {
    try {
      final String jsonString = await rootBundle.loadString(
        'assets/content/vocabulary_data.json',
      );
      final List<dynamic> jsonData = json.decode(jsonString);
      return jsonData;
    } catch (e) {
      throw Exception('加载词汇数据失败: $e');
    }
  }

  /// 构建拼音内容展示
  Widget _buildPinyinContent() {
    // 对于拼音类型，直接显示拼音符号列表
    return FutureBuilder<List<dynamic>>(
      future: _loadPinyinData(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('加载失败: ${snapshot.error}'));
        } else if (snapshot.hasData) {
          final data = snapshot.data!;
          
          // 从item的contentRef中提取拼音类型
          final pinyinTypeId = widget.item.contentRef ?? '';
          int pinyinTypeIndex = 0;
          
          if (pinyinTypeId.contains('shengmu')) {
            pinyinTypeIndex = 0;
          } else if (pinyinTypeId.contains('yunmu')) {
            pinyinTypeIndex = 1;
          } else if (pinyinTypeId.contains('zhengtirendu')) {
            pinyinTypeIndex = 2;
          }
          
          if (pinyinTypeIndex < data.length) {
            final pinyinType = data[pinyinTypeIndex];
            final symbols = List<Map<String, dynamic>>.from(pinyinType['symbols'] ?? []);
            
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 类型标题
                Text(
                  pinyinType['title'] ?? '拼音',
                  style: const TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                ),
                
                const SizedBox(height: 8),
                
                // 类型描述
                if (pinyinType['description'] != null)
                  Text(
                    pinyinType['description'],
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.grey,
                    ),
                    textAlign: TextAlign.center,
                  ),
                
                const SizedBox(height: 16),
                
                // 拼音符号列表
                Expanded(
                  child: GridView.builder(
                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 9, // 每行显示9个
                      crossAxisSpacing: 4,
                      mainAxisSpacing: 4,
                    ),
                    itemCount: symbols.length,
                    itemBuilder: (context, index) {
                      final symbol = symbols[index];
                      return Card(
                        child: Center(
                          child: Text(
                            symbol['symbol'] ?? '',
                            style: const TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ],
            );
          } else {
            return const Center(child: Text('未找到指定拼音类型'));
          }
        } else {
          return const Center(child: Text('暂无数据'));
        }
      },
    );
  }

  Future<List<dynamic>> _loadPinyinData() async {
    try {
      final String jsonString = await rootBundle.loadString(
        'assets/content/pinyin_data.json',
      );
      final List<dynamic> jsonData = json.decode(jsonString);
      return jsonData;
    } catch (e) {
      throw Exception('加载拼音数据失败: $e');
    }
  }


  Widget _buildBottomBar() {
    return BottomActionBar(
      isLiked: _isLiked,
      isCollected: _isCollected,
      onLikePressed: () {
        _onLikePressed();
        widget.onLike();
      },
      onCollectPressed: _onCollectPressed,
      onCategoryPressed: widget.onCategory,
      onSpeakPressed: () => _speakContent(),
    );
  }

  /// 朗读内容
  Future<void> _speakContent() async {
    if (!_ttsSupported) return;
    
    try {
      // 对于英文故事，只朗读英文部分
      if (widget.item.subject == 'English' && widget.item.module == 'Stories') {
        final parts = widget.item.content.split('\n\n');
        final englishContent = parts.isNotEmpty ? parts[0] : widget.item.content;
        await flutterTts.speak(englishContent);
      } else {
        await flutterTts.speak(widget.item.content);
      }
    } catch (e) {
      print("Error speaking content: $e");
    }
  }

  @override
  void dispose() {
    if (_ttsSupported && !kIsWeb) {
      flutterTts.stop();
    }
    super.dispose();
  }
}